<template>
  <div class="tinymce-container editor-container">
    <textarea class="tinymce-textarea" height:700 :id="tinymceId" style="text-align:justify"></textarea>
    <div class="editor-custom-btn-container">
      <editorImage color="#1890ff" class="editor-upload-btn uploadPic" @successCBK="imageSuccessCBK"></editorImage>
    </div>
    <div class="formatbox" style="margin-top:18px">
        <el-button type="primary" size="small" id="formatBtn" @click="formatFun">格式化</el-button>
        <el-button type="danger" size="small" id="formatBtn" @click="formatMark">半角符号转全角符号</el-button>
    </div>
    <el-dialog
  title="标点符号半角转全角内容确认"
  :visible.sync="dialogVisible"
  width="40%">
  <div v-html="confirmContent"></div>
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="formatContent">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
import editorImage from './components/editorImage'
import plugins from './plugins'
import toolbar from './toolbar'

export default {
  name: 'tinymce',
  components: { editorImage },
  inject: ['reload'],
  props: {
    id: {
      type: String
    },
    value: {
      type: String,
      default: ''
    },
    toolbar: {
      type: Array,
      required: false,
      default() {
        return []
      }
    },
    menubar: {
      default: 'file edit insert view format table'
    },
    height: {
      type: Number,
      required: false,
      default: 360
    }
  },
  data() {
    return {
      dialogVisible: false,
      hasChange: false,
      hasInit: false,
      styleCon: '',
      tranSize: '',
      confirmContent: '',
      tinymceId: this.id || 'vue-tinymce-' + +new Date()
    }
  },
  watch: {
    value(val) {
      if (!this.hasChange && this.hasInit) {
        // console.log(44444444444)
        this.$nextTick(() =>
          window.tinymce.get(this.tinymceId).setContent(val)
        )
        console.log(val)
      }
    }
  },
  mounted() {
    this.initTinymce()
  },
  activated() {
    this.initTinymce()
  },
  deactivated() {
    this.destroyTinymce()
  },
  methods: {
    formatMark() {
      this.mark(this.value)
      this.dialogVisible = true
    },
    formatFun() {
      // this.tranSize = this.styleCon.replace(
      //   /<p([^<>]*)>([^<>]*)<\/p>/gi,
      //   '<p$1 style="text-indent:2em;line-height:24px;">$2</p>'
      // )
      this.loop(this.value)
      this.tranSize =
        "<div style='text-align:justify'>" + this.tranSize + '</div>'
      window.tinymce.get(this.tinymceId).setContent(this.tranSize)
      this.$emit('changecontent', this.tranSize)
    },
    formatContent() {
      window.tinymce.get(this.tinymceId).setContent(this.tranSize)
      this.$emit('changecontent', this.tranSize)
      this.dialogVisible = false
    },
    tranCdstr(str) {
      const reg = /<(a\w+|[^a]\w*)(.*?)>(.*?)<\/\1>/g
      while (reg.test(str)) {
        str = str.replace(reg, '【LEFT】$2【TAGEND】$3【END】')
      }
      return str
    },
    mark(str) {
      // str = this.tranCdstr(str);
      str = this.toDBC(str)
      this.tranSize = this.transforContent(str)
      this.confirmContent = this.transforContent(this.confirmContent)
    },
    loop(str) {
      str = this.tranCdstr(str)
      str = this.transforContent(str)
      this.tranSize = str
        // .replace(/style="[^"]+"/ig, '')
        .replace(/<div style='text-align:justify'>/g, '')
        .replace(/<\/div>/g, '')
        .replace(/<br\s*\/?>/gi, '<br>')
        .replace(
          /<p([^>])*>(?=([^<]*)<img([^>])*>)/gi,
          '<p style="text-indent:2em;">'
        )
        .replace(/&nbsp;/g, '')
        .replace(/<([a-z]+?)(?:\s+?[^>]*?)?>\s*?<\/\1>/gi, '')
        .replace(
          /<img src/g,
          '<img class="wscnph" style="display: block;" src'
        )
    },
    transforContent(str) {
      str = str
        .replace(
          /【LEFT】 style="text-indent: 2em;"【TAGEND】&nbsp;【END】/g,
          ''
        )
        .replace(/【LEFT】【TAGEND】&nbsp;【END】/g, '')
        .replace(/【LEFT】/g, '<p style="text-indent:2em;"')
        .replace(/【TAGEND】/g, '>')
        .replace(/【END】/g, '</p><p style="text-indent:2em;"><br/></p>')

      return str
    },
    toDBC(str) {
      let tmp = ''
      let content = ''
      for (let i = 0; i < str.length; i++) {
        let unicode = str.charCodeAt(i)
        if (
          unicode == 33 || // !
          unicode == 35 || // #
          unicode == 36 || // $
          unicode == 40 || // (
          unicode == 41 || // )
          unicode == 42 || // *
          unicode == 43 || // +
          unicode == 44 || // ,
          unicode == 46 || // .
          unicode == 64 || // @
          unicode == 123 || // {
          unicode == 124 || // |
          unicode == 125 || // }
          unicode == 126 // ~
        ) {
          tmp = tmp + String.fromCharCode(unicode + 65248)
          content =
            content +
            '<span style="background:#f56c6c;color:white">' +
            String.fromCharCode(unicode + 65248) +
            '</span>'
          console.log(content)
        } else {
          tmp += String.fromCharCode(unicode)
          content += String.fromCharCode(unicode)
        }
      }
      this.confirmContent = content
      return tmp
    },
    initTinymce() {
      const _this = this
      window.tinymce.init({
        font_formats: ['宋体=宋体', '黑体=黑体', '楷体=楷体', '仿宋=仿宋'].join(
          ';'
        ),
        selector: `#${this.tinymceId}`,
        language_url: './static/tinymce4.7.5/langs/zh_CN.js',
        height: this.height,
        body_class: 'panel-body ',
        object_resizing: false,
        toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar,
        menubar: this.menubar,
        plugins: plugins,
        end_container_on_empty_block: true,
        powerpaste_word_import: 'clean',
        code_dialog_height: 450,
        code_dialog_width: 1000,
        advlist_bullet_styles: 'square',
        advlist_number_styles: 'default',
        imagetools_cors_hosts: ['www.tinymce.com', 'codepen.io'],
        default_link_target: '_blank',
        link_title: false,
        // tinyMCE粘贴word/html时去掉文本里的样式
        paste_auto_cleanup_on_paste: true,
        paste_remove_styles: true,
        paste_remove_styles_if_webkit: true,
        paste_strip_class_attributes: true,
        // tinyMCE粘贴word/html时去掉文本里的样式
        paste_webkit_styles: false,
        init_instance_callback: editor => {
          if (_this.value) {
            editor.setContent(_this.value)
          }
          _this.hasInit = true
          editor.on('NodeChange Change KeyUp SetContent', () => {
            this.hasChange = true
            this.styleCon = editor.getContent()
            this.$emit('input', editor.getContent())
          })
        }
        // 整合七牛上传
        // images_dataimg_filter(img) {
        //   setTimeout(() => {
        //     const $image = $(img);
        //     $image.removeAttr('width');
        //     $image.removeAttr('height');
        //     if ($image[0].height && $image[0].width) {
        //       $image.attr('data-wscntype', 'image');
        //       $image.attr('data-wscnh', $image[0].height);
        //       $image.attr('data-wscnw', $image[0].width);
        //       $image.addClass('wscnph');
        //     }
        //   }, 0);
        //   return img
        // },
        // images_upload_handler(blobInfo, success, failure, progress) {
        //   progress(0);
        //   const token = _this.$store.getters.token;
        //   getToken(token).then(response => {
        //     const url = response.data.qiniu_url;
        //     const formData = new FormData();
        //     formData.append('token', response.data.qiniu_token);
        //     formData.append('key', response.data.qiniu_key);
        //     formData.append('file', blobInfo.blob(), url);
        //     upload(formData).then(() => {
        //       success(url);
        //       progress(100);
        //     })
        //   }).catch(err => {
        //     failure('出现未知问题，刷新页面，或者联系程序员')
        //     console.log(err);
        //   });
        // },
      })
    },

    destroyTinymce() {
      if (window.tinymce.get(this.tinymceId)) {
        window.tinymce.get(this.tinymceId).destroy()
      }
    },
    setContent(value) {
      window.tinymce.get(this.tinymceId).setContent(value)
    },
    getContent() {
      window.tinymce.get(this.tinymceId).getContent()
    },
    imageSuccessCBK(arr) {
      const _this = this
      const iframe = document.querySelector('iframe')
      arr.forEach(v => {
        window.tinymce
          .get(_this.tinymceId)
          .insertContent(
            `<img class="wscnph" style="display:block;" width="100%" src="${
              v.url
            }" imgid="${v.fileid}">`
          )
      })
      iframe.style.height = `${iframe.clientWidth * arr.length}px`
    }
  },
  destroyed() {
    this.destroyTinymce()
  }
}
</script>

<style scoped>
.tinymce-container {
  position: relative;
}
.tinymce-container >>> .mce-fullscreen {
  z-index: 10000;
}
.tinymce-textarea {
  visibility: hidden;
  z-index: -1;
}
.editor-custom-btn-container {
  position: absolute;
  right: 4px;
  top: 4px;
  /*z-index: 2005;*/
}
.editor-upload-btn {
  display: inline-block;
}
.wscnph {
  display: block !important;
}
</style>
